package com.qf.service.impl;

import com.qf.entity.DevUser;
import com.qf.service.SendMailService;
import com.qf.util.Base64Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 *  执行发送邮件
 *      **编写配置信息**
 *  在注册中发送邮件设置为异步操作 @Async  （同时在启动类上@EnableAsync）
 *  防止因为发送邮件时间过长迟迟无法完成注册操作
 *
 */

@Service
@Slf4j
public class SendMailServiceImpl implements SendMailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.activeUrl}")
    private String activeUrl;

    @Override
    @Async
    public void sendMail(DevUser devUser) {

        //创建邮箱对象
        MimeMessage msg = javaMailSender.createMimeMessage();
        //给msg邮件设置信息
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(msg,true);
            //设置4个基本信息  收件人、发件人、主题、内容
            messageHelper.setFrom(from);
            messageHelper.addTo(devUser.getDevEmail());
            messageHelper.setSubject("APP开发者账号激活邮件");
            String url = activeUrl + "/dev/user/active?email=" + Base64Utils.encode(devUser.getDevEmail()) + "&code=" + Base64Utils.encode(devUser.getDevCode());
            messageHelper.setText("text/html;charset=utf-8",devUser.getDevUsername() + ",您好<br /> 欢迎注册APP管理平台! 请点击链接进行激活:<a href='"+url+"'>"+url+"</a>");

            //执行发送
            javaMailSender.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            log.error("【发送激活邮件】发送激活邮件失败！");

        }
    }
}
